﻿// This code is released under the BSD license.
namespace PugLib.Threading
{
    using System.ComponentModel;

    /// <summary>
    /// http://www.pluralsight.com/blogs/mike/archive/2005/10/24/15875.aspx
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class BackgroundWorkerCompletedHandler<T>
    {
        private readonly BackgroundWorker _bgw;
        private readonly RunWorkerCompletedEventHandler _completedHandler;
        private readonly T _userState;
        private object _sender;

        public BackgroundWorkerCompletedHandler(BackgroundWorker bgw, RunWorkerCompletedEventHandler completedHandler,
                                                T userState)
        {
            _bgw = bgw;
            _userState = userState;
            _completedHandler = completedHandler;
            _sender = null;
            _bgw.RunWorkerCompleted += OnRunWorkerCompleted;
        }

        public BackgroundWorker BackgroundWorker
        {
            get { return _bgw; }
        }

        public T UserState
        {
            get { return _userState; }
        }

        public object Sender
        {
            get { return _sender; }
        }

        private void OnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs eventArgs)
        {
            _sender = sender;

            try
            {
                _completedHandler(this, eventArgs);
            }
            finally
            {
                _bgw.RunWorkerCompleted -= OnRunWorkerCompleted;
            }
        }
    }
}